//
// Created by WenDaojiang on 15/11/22.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "GeTuiPlugin.h"
#import "HybridBridge.h"

static void uncaughtExceptionHandler(NSException *exception) {
    NSLog(@"CRASH: %@", exception);
    NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
}

@interface GeTuiPlugin(){
    NSString *_appId;
    NSString *_appKey;
    NSString *_appSecret;
}
@end

@implementation GeTuiPlugin

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initializeGeTui];
    }

    return self;
}

- (void)initializeGeTui {

    NSLog(@"[GeTuiSdk version] %@", [GeTuiSdk version]);

    NSDictionary *launchOptions = [HybridEventBus defaultEventBus].launchOptions;

    //[self startSdkWith:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret];
    [self startSdk];

    // 注册APNS
    [self registerRemoteNotification];

    // 处理远程通知启动APP
    //[self receiveNotificationByLaunchingOptions:launchOptions];]

    // [2-EXT]: 获取启动时收到的APN数据
    NSDictionary *message = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (message) {
        NSString *payloadMsg = message[@"payload"];
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
        NSLog(@"payloadMsg record %@", record);
    }

    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

    [[HybridEventBus defaultEventBus] subscribe:@"setPushSwitch" UsingBlock:^(NSNotification *notification) {
        NSLog(@"setPushSwitch %@" , notification.userInfo);
        BOOL pushOff = [notification.userInfo[@"pushOff"] boolValue];
        [GeTuiSdk setPushModeForOff:pushOff];
    }];
    //[[NSNotificationCenter defaultCenter] addObserverForName:@"GeTuiSdkDidReceivePayload" object:self queue:<#(NSOperationQueue *)queue#> usingBlock:<#(void (^)(NSNotification *note))block#>]
}


- (void)enterBackground {
    //[GeTuiSdk enterBackground];
    NSLog(@"APP进入后台时，通知个推SDK进入后台");
    [self dispatchEvent:@"background" data:@""];
}

- (void)enterForeground {
    NSLog(@"APP进入前台时，通知个推SDK进入前台");
    [self dispatchEvent:@"foreground" data:@""];
}

- (void)didBecomeActive {
    //[self startSdkWith:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret];
    [self startSdk];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    NSLog(@"APP applicationDidBecomeActive ，通知个推SDK进入applicationDidBecomeActive");
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {

    if (completionHandler) {

        // 处理APNs代码，通过userInfo可以取到推送的信息（包括内容，角标，自定义参数等）。如果需要弹窗等其他操作，则需要自行编码。
        NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);

        completionHandler(UIBackgroundFetchResultNewData);
    }
}

- (void)didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"didReceiveLocalNotification %@", notification.userInfo);
    if (notification.userInfo[@"notification"] != nil){
        [self dispatchEvent:@"receiveLocalNotification" data:notification.userInfo[@"notification"]];
    }
}


- (void)performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {

    [GeTuiSdk resume];
    NSLog(@"[GeTuiSdk resume]");
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    [GeTuiSdk registerDeviceToken:@""];     /// 如果APNS注册失败，通知个推服务器
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}

- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSString *myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    myToken = [myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    [GeTuiSdk registerDeviceToken:myToken];    /// 向个推服务器注册deviceToken
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", myToken);
}

// 个推委托

//SDK设置推送模式回调
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        NSLog(@"GeTui %@", [NSString stringWithFormat:@">>>[SetModeOff error]: %@", [error localizedDescription]]);
        return;
    }

    NSLog(@"GeTui %@", [NSString stringWithFormat:@">>>[GexinSdkSetModeOff]: %@", isModeOff ? @"开启" : @"关闭"]);

}

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    [KVStorage setKey:@"GeTuiClientId" Value:clientId];
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}

/** SDK收到透传消息回调 */

- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }

    NSDictionary *payload = @{
            //@"payloadId" : payloadId,
            @"taskId" : taskId,
            @"msgId" : msgId,
            @"payloadMsg" : payloadMsg,
            @"offLine" : @(offLine)
    };
    [self dispatchEvent:@"GeTuiSdkDidReceivePayload" data:payload];
    [[HybridEventBus defaultEventBus] postData:payload Tag:@"GeTuiSdkDidReceivePayload"];

    [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];

    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
}

//

- (void)registerRemoteNotification {

#ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        //IOS8 新的通知机制category注册
        UIMutableUserNotificationAction *action1;
        action1 = [[UIMutableUserNotificationAction alloc] init];
        [action1 setActivationMode:UIUserNotificationActivationModeBackground];
        [action1 setTitle:@"取消"];
        [action1 setIdentifier: NotificationCategoryIdent];
        [action1 setDestructive:NO];
        [action1 setAuthenticationRequired:NO];

        UIMutableUserNotificationAction *action2;
        action2 = [[UIMutableUserNotificationAction alloc] init];
        [action2 setActivationMode:UIUserNotificationActivationModeBackground];
        [action2 setTitle:@"回复"];
        [action2 setIdentifier: NotificationActionTwoIdent];
        [action2 setDestructive:NO];
        [action2 setAuthenticationRequired:NO];

        UIMutableUserNotificationCategory *actionCategory;
        actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier: NotificationCategoryIdent];
        [actionCategory setActions:@[action1, action2]
                        forContext:UIUserNotificationActionContextDefault];

        NSSet *categories = [NSSet setWithObject:actionCategory];
        UIUserNotificationType types = (UIUserNotificationTypeAlert|
                UIUserNotificationTypeSound|
                UIUserNotificationTypeBadge);

        UIUserNotificationSettings *settings;
        settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                UIRemoteNotificationTypeSound|
                UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                   UIRemoteNotificationTypeSound|
                                                                   UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif

}

-(void) stopSdk {
    //[GeTuiSdk stopSdk];
    [GeTuiSdk destroy];
}


- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret {
    //[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    //[GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self];
    //NSLog(@"gt   %@,%@,%@", appID, appKey, appSecret);
    //NSError *error;
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self];
    /*if(error){
        NSLog(@"GeTuiSdk startSdkWith Error: %@", error);
    }*/

    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    //[1-3]:设置电子围栏功能，开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
}

- (void)startSdk{
    if (_appId == nil || _appKey == nil){

        NSDictionary *geTuiInfo = [[HybridBridge defaultHybridBridge] appInfo][@"GeTui"];
        if (IS_DEBUG){
            NSDictionary *GeTuiDebug = [HybridBridge defaultHybridBridge].appInfo[@"GeTuiDebug"];
            if (GeTuiDebug != nil)geTuiInfo = GeTuiDebug;
        }

        NSLog(@"geTuiInfo %@",geTuiInfo);
        if(!geTuiInfo || !geTuiInfo[@"AppId"]){
            NSLog(@"个推配置信息错误.");
            return;
        }
        _appId = geTuiInfo[@"AppId"];
        _appKey = geTuiInfo[@"AppKey"];
        _appSecret = geTuiInfo[@"AppSecret"];
    }
    [self startSdkWith:_appId appKey:_appKey appSecret:_appSecret];
}

- (void)setDeviceToken:(NSString *)aToken {

    [GeTuiSdk registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error {
    return [GeTuiSdk setTags:aTags];
}

- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {

    return [GeTuiSdk sendMessage:body error:error];
}

- (void)bindAlias:(NSString *)aAlias {
    [GeTuiSdk bindAlias:aAlias andSequenceNum:@""];
}

- (void)unbindAlias:(NSString *)aAlias {
    [GeTuiSdk unbindAlias:aAlias andSequenceNum:@""];
}


@end